/** @file
  Functions that loads image from FV

 @copyright
  INTEL CONFIDENTIAL
  Copyright 1999 - 2016 Intel Corporation.

  The source code contained or described herein and all documents related to the
  source code ("Material") are owned by Intel Corporation or its suppliers or
  licensors. Title to the Material remains with Intel Corporation or its suppliers
  and licensors. The Material may contain trade secrets and proprietary and
  confidential information of Intel Corporation and its suppliers and licensors,
  and is protected by worldwide copyright and trade secret laws and treaty
  provisions. No part of the Material may be used, copied, reproduced, modified,
  published, uploaded, posted, transmitted, distributed, or disclosed in any way
  without Intel's prior express written permission.

  No license under any patent, copyright, trade secret or other intellectual
  property right is granted to or conferred upon you by disclosure or delivery
  of the Materials, either expressly, by implication, inducement, estoppel or
  otherwise. Any license under such intellectual property rights must be
  express and approved by Intel in writing.

  Unless otherwise agreed by Intel in writing, you may not remove or alter
  this notice or any other notice embedded in Materials by Intel or
  Intel's suppliers or licensors in any way.

  This file contains a 'Sample Driver' and is licensed as such under the terms
  of your license agreement with Intel or your vendor. This file may be modified
  by the user, subject to the additional terms of the license agreement.

@par Specification Reference:
**/

#include "GetImage.h"
#include <Protocol/FirmwareVolume2.h>
#include <Protocol/LoadedImage.h>
#include <Library/DebugLib.h>
#include <Library/UefiBootServicesTableLib.h>

EFI_STATUS
GetImageFromFv (
  IN  EFI_FIRMWARE_VOLUME2_PROTOCOL * Fv,
  IN  EFI_GUID                      * NameGuid,
  IN  EFI_SECTION_TYPE              SectionType,
  OUT VOID                          **Buffer,
  OUT UINTN                         *Size
  )
/**

  @brief
  Get an image from firmware volume

  @param[in] Fv                     The firmware volume protocol instance
  @param[in] NameGuid               GUID of file
  @param[in] SectionType            Type of section
  @param[out] Buffer                Image content buffer
  @param[out] Size                  Image size

  @retval EFI_SUCCESS               Successfully completed.
  @retval EFI_WARN_BUFFER_TOO_SMALL Too small a buffer is to contain image content
  @retval EFI_ACCESS_DENIED         Access firmware volume error.

**/
{
  EFI_STATUS              Status;
  EFI_FV_FILETYPE         FileType;
  EFI_FV_FILE_ATTRIBUTES  Attributes;
  UINT32                  AuthenticationStatus;

  ///
  /// Read desired section content in NameGuid file
  ///
  *Buffer = NULL;
  *Size   = 0;
  Status = Fv->ReadSection (
                Fv,
                NameGuid,
                SectionType,
                0,
                Buffer,
                Size,
                &AuthenticationStatus
                );

  if (EFI_ERROR (Status) && (SectionType == EFI_SECTION_TE)) {
    ///
    /// Try reading PE32 section, since the TE section does not exist
    ///
    *Buffer = NULL;
    *Size   = 0;
    Status = Fv->ReadSection (
                  Fv,
                  NameGuid,
                  EFI_SECTION_PE32,
                  0,
                  Buffer,
                  Size,
                  &AuthenticationStatus
                  );
  }

  if (EFI_ERROR (Status) && ((SectionType == EFI_SECTION_TE) || (SectionType == EFI_SECTION_PE32))) {
    ///
    /// Try reading raw file, since the desired section does not exist
    ///
    *Buffer = NULL;
    *Size   = 0;
    Status = Fv->ReadFile (
                  Fv,
                  NameGuid,
                  Buffer,
                  Size,
                  &FileType,
                  &Attributes,
                  &AuthenticationStatus
                  );
  }

  return Status;
}

EFI_STATUS
GetImageEx (
  IN  EFI_HANDLE         ImageHandle,
  IN  EFI_GUID           *NameGuid,
  IN  EFI_SECTION_TYPE   SectionType,
  OUT VOID               **Buffer,
  OUT UINTN              *Size,
  BOOLEAN                WithinImageFv
  )
/**

  @brief
  Get specified image from a firmware volume.

  @param[in] ImageHandle          Image handle for the loaded driver
  @param[in] NameGuid             File name GUID
  @param[in] SectionType          Section type
  @param[in] Buffer               Bufer to contain image
  @param[in] Size                 Image size
  @param[in] WithinImageFv        Whether or not in a firmware volume

  @retval EFI_INVALID_PARAMETER   Invalid parameter
  @retval EFI_NOT_FOUND           Can not find the file
  @retvalEFI_SUCCESS             Successfully completed

**/
{
  EFI_STATUS                    Status;
  EFI_HANDLE                    *HandleBuffer;
  UINTN                         HandleCount;
  UINTN                         Index;
  EFI_LOADED_IMAGE_PROTOCOL     *LoadedImage;
  EFI_FIRMWARE_VOLUME2_PROTOCOL *ImageFv;
  EFI_FIRMWARE_VOLUME2_PROTOCOL *Fv;

  DEBUG ((DEBUG_INFO, "GetImageEx() Start\n"));

  if (ImageHandle == NULL && WithinImageFv) {
    return EFI_INVALID_PARAMETER;
  }

  Status  = EFI_NOT_FOUND;
  ImageFv = NULL;
  if (ImageHandle != NULL) {
    Status = gBS->HandleProtocol (
                    ImageHandle,
                    &gEfiLoadedImageProtocolGuid,
                    (VOID **) &LoadedImage
                    );
    if (EFI_ERROR (Status)) {
      return Status;
    }

    Status = gBS->HandleProtocol (
                    LoadedImage->DeviceHandle,
                    &gEfiFirmwareVolume2ProtocolGuid,
                    (VOID **) &ImageFv
                    );
    if (!EFI_ERROR (Status)) {
      Status = GetImageFromFv (ImageFv, NameGuid, SectionType, Buffer, Size);
    }
  }

  if (Status == EFI_SUCCESS || WithinImageFv) {
    return Status;
  }

  Status = gBS->LocateHandleBuffer (
                  ByProtocol,
                  &gEfiFirmwareVolume2ProtocolGuid,
                  NULL,
                  &HandleCount,
                  &HandleBuffer
                  );
  if (EFI_ERROR (Status)) {
    return Status;
  }
  ///
  /// Find desired image in all Fvs
  ///
  for (Index = 0; Index < HandleCount; ++Index) {
    Status = gBS->HandleProtocol (
                    HandleBuffer[Index],
                    &gEfiFirmwareVolume2ProtocolGuid,
                    (VOID **) &Fv
                    );

    if (EFI_ERROR (Status)) {
      (gBS->FreePool) (HandleBuffer);
      return Status;
    }

    if (ImageFv != NULL && Fv == ImageFv) {
      continue;
    }

    Status = GetImageFromFv (Fv, NameGuid, SectionType, Buffer, Size);

    if (!EFI_ERROR (Status)) {
      break;
    }
  }
  (gBS->FreePool) (HandleBuffer);

  ///
  /// Not found image
  ///
  if (Index == HandleCount) {
    return EFI_NOT_FOUND;
  }

  DEBUG ((DEBUG_INFO, "GetImageEx() End\n"));

  return EFI_SUCCESS;
}
